import 'dart:convert';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:opene/JhPickerTool.dart';
import 'package:opene/app_theme.dart';
import 'package:opene/app_utils.dart';
import 'package:opene/base/base_state.dart';
import 'package:opene/base/loading.dart';
import 'package:opene/base/scan_code.dart';
import 'package:opene/net/method/base_method.dart';
import 'package:opene/net/network_manager.dart';
import 'package:opene/net/response/base_response.dart';
import 'package:opene/ui/checkin/checkinverifypage.dart';
import 'package:opene/utils/ImageUtils.dart';
import 'package:toast/toast.dart';

import '../../app_constant.dart';
import 'checkinmodel.dart';

class CheckinReceived extends StatelessWidget {
  CheckinInfo data;
  int type;

  CheckinReceived({this.data, this.type});

  @override
  Widget build(BuildContext context) {
    return CheckinReceivedPage(checkinInfo: data, type: type);
  }
}

class CheckinReceivedPage extends StatefulWidget {
  CheckinInfo checkinInfo;
  int type;

  CheckinReceivedPage({this.checkinInfo, this.type});

  @override
  _CheckinReceivedPageState createState() => _CheckinReceivedPageState(checkinInfo: checkinInfo, type1: type);
}

class _CheckinReceivedPageState extends BaseState<CheckinReceivedPage> {
  CheckinInfo checkinInfo;
  int type1;

  _CheckinReceivedPageState({this.checkinInfo, this.type1});

  final TextEditingController dateController = TextEditingController();

  bool layoutQty = false, layoutDock = false, tvPhoto = false, rv = false;

  final controller = ScrollController();
  String containerNo;
  String typeValue;
  String uniqId;
  String strDate, tvContainerNoHint = "Container NO#: ", tvTimeHint = "Drop Date: ";
  List<PhotoBean> damages = new List();

  int index = 0, position;

  @override
  String setTitle({String title}) {
    return !Utils.isEmpty(title) ? title : "Checkin";
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    setResetGone();
    setState(() {
      next = "Submit";
      strDate = checkinInfo.dropDate;
      type = type1;
      containerNo = checkinInfo.containerNo;
      typeValue = checkinInfo.type;
      uniqId = checkinInfo.uniqId;
      textEditingController.text = checkinInfo.checkinDock;

      if (type == 2) {
        setTitle(title: 'Container Empty');
        tvTimeHint = "Empty Date: ";
      } else if (type == 3) {
        setTitle(title: 'EmptyContainer Returned');
        layoutDock = false;
        layoutQty = false;
        tvTimeHint = "Return Date: ";
        tvPhoto = false;
        rv = false;
      }

      if (checkinInfo.damaged != null && checkinInfo.damaged.length > 0) {
        checkinInfo.damaged.forEach((value) {
          if (!Utils.isEmpty(value)) {
            PhotoBean photoBeanTemp = new PhotoBean();
            photoBeanTemp.urlImg = value;
            damages.add(photoBeanTemp);
          }
        });
      }
      damages.add(new PhotoBean());

    });
  }

  Future pickImages(context) async {
    File image = await ImageUtils.chosePhotoOnAlbumOrCamera(context: context);
    print(image.path);
    String name = "";
    setState(() {
      PhotoBean photoBean = new PhotoBean();
      photoBean.image = image;
      damages.insert(position, photoBean);
      name = "damage";
      fileUpload(containerNo, "checkin", image, name, index, position, false, false);
      print("index:${index},position:${position}");
      print(image.path);
    });
  }

  @override
  Widget getViewBinding() {
    return Padding(
      padding: const EdgeInsets.only(left: 0, top: 10, right: 0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            margin: EdgeInsets.only(left: 15),
            child: Row(
              children: [
                Text(
                  "Container NO#: ",
                  style: TextStyle(color: MyAppTheme.color_666666, fontSize: 14.0),
                ),
                Text(
                  Utils.getStringisEmpty(containerNo),
                  style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0),
                ),
              ],
            ),
          ),
          Container(
            margin: EdgeInsets.only(left: 15),
            child: Row(
              children: [
                Text(
                  "Type: ",
                  style: TextStyle(color: MyAppTheme.color_666666, fontSize: 14.0),
                ),
                Text(
                  Utils.getStringisEmpty(typeValue),
                  style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0),
                ),
              ],
            ),
          ),
          Container(
            margin: EdgeInsets.only(left: 15),
            child: Row(
              children: [
                Text(
                  "Uniq ID: ",
                  style: TextStyle(color: MyAppTheme.color_666666, fontSize: 14.0),
                ),
                Text(
                  Utils.getStringisEmpty(uniqId),
                  style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0),
                ),
              ],
            ),
          ),
          Row(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              Expanded(
                flex: 1, //设置权重
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Container(
                      padding: EdgeInsets.zero,
                      margin: EdgeInsets.zero,
                      height: 25.0,
                      child: Radio<int>(
                        materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
                        value: 1,
                        groupValue: this.type,
                        activeColor: MyAppTheme.nearlyBlue,
                        onChanged: null,
                      ),
                    ),
                    Text(
                      'Container',
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(color: this.type == 1 ? MyAppTheme.nearlyBlue : MyAppTheme.color_333333, fontSize: 12.0),
                    ),
                  ],
                ),
              ),
              Expanded(
                flex: 1, //设置权重
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Container(
                      padding: EdgeInsets.zero,
                      margin: EdgeInsets.zero,
                      height: 25.0,
                      child: Radio<int>(
                        materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
                        value: 2,
                        groupValue: this.type,
                        activeColor: MyAppTheme.nearlyBlue,
                        onChanged: null,
                      ),
                    ),
                    Text(
                      'Truck',
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(color: this.type == 2 ? MyAppTheme.nearlyBlue : MyAppTheme.color_333333, fontSize: 12.0),
                    ),
                  ],
                ),
              ),
              Expanded(
                flex: 1, //设置权重
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Container(
                      padding: EdgeInsets.zero,
                      margin: EdgeInsets.zero,
                      height: 25.0,
                      child: Radio<int>(
                        materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
                        value: 3,
                        groupValue: this.type,
                        activeColor: MyAppTheme.nearlyBlue,
                        onChanged: null,
                      ),
                    ),
                    Text(
                      'Package',
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(color: this.type == 3 ? MyAppTheme.nearlyBlue : MyAppTheme.color_333333, fontSize: 12.0),
                    ),
                  ],
                ),
              ),
            ],
          ),
          Visibility(
            visible: layoutDock,
            child: Container(
              margin: const EdgeInsets.only(left: 15, top: 5, right: 15, bottom: 0),
              width: double.infinity,
              child: ConstrainedBox(
                constraints: BoxConstraints(maxHeight: 40),
                child: TextField(
                  controller: textEditingController,
                  textInputAction: TextInputAction.search,
                  onSubmitted: (String text) {
                    print('Searching for $text');
                  },
                  // autofocus: true,
                  decoration: InputDecoration(
                    suffixIcon: IconButton(
                      icon: Icon(
                        Icons.qr_code_scanner,
                        size: 25,
                        color: MyAppTheme.nearlyBlue,
                      ),
                      onPressed: () {
                        // requestPermissions();
                        // Utils.scanBarcode(context);
                        Navigator.of(context).push(MaterialPageRoute(builder: (context) {
                          return ScanCode();
                        })).then((text) {
                          if (text == null) {
                            return;
                          }
                          print(text); //拿到扫描结果
                        });
                      },
                    ),
                    border: OutlineInputBorder(
                      borderSide: BorderSide(
                        color: MyAppTheme.nearlyBlue,
                      ),
                      borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                    ),
                    enabledBorder: OutlineInputBorder(
                      borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                      // 设置焦点之外的边框颜色
                      borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                    ),
                    focusedBorder: OutlineInputBorder(
                      borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                      // 设置焦点时的边框颜色
                      borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                    ),
                    hintText: "please scan the dock num",
                    filled: true,
                    fillColor: MyAppTheme.white,
                    //隐藏下划线
                    //border: InputBorder.none,
                    hintStyle: TextStyle(color: Colors.grey),
                    contentPadding: const EdgeInsets.symmetric(vertical: 0, horizontal: 15),
                  ),
                  onChanged: (text) {
                    if (text == null) {
                      code = text;
                      return;
                    }
                    if ((code != null) && (code == text)) {
                      return;
                    }
                    code = text;
                  },
                ),
              ),
            ),
          ),
          Container(
            height: 40,
            margin: const EdgeInsets.only(left: 15, top: 3, right: 15, bottom: 0),
            width: double.infinity,
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                Text(
                  tvTimeHint,
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(color: MyAppTheme.color_666666, fontSize: 12.0),
                ),
                Expanded(
                  flex: 1, //设置权重
                  child: GestureDetector(
                    onTap: () {
                      // 请求焦点
                      FocusScope.of(context).requestFocus(FocusNode());

                      JhPickerTool.showDatePicker(context, clickCallback: (var timeStr, var str) {
                        print(timeStr);
                        print(str);
                        setState(() {
                          strDate = timeStr;
                        });
                      });
                    },
                    child: Container(
                      height: 40,
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.all(Radius.circular(20.0)),
                        color: MyAppTheme.white,
                        border: Border.all(
                          color: MyAppTheme.nearlyBlue,
                          width: 1.0,
                        ),
                      ),
                      child: Row(
                        children: [
                          Container(
                            margin: const EdgeInsets.only(left: 0, top: 0, right: 9, bottom: 0),
                            width: 1,
                          ),
                          Expanded(
                            flex: 1, //设置权重
                            child: Text(
                              Utils.getStringisEmpty(strDate),
                              maxLines: 1,
                              overflow: TextOverflow.ellipsis,
                              style: TextStyle(color: MyAppTheme.color_333333),
                            ),
                          ),
                          Icon(
                            Icons.date_range,
                            size: 25,
                            color: MyAppTheme.nearlyBlue,
                          ),
                          Container(
                            margin: const EdgeInsets.only(left: 0, top: 0, right: 9, bottom: 0),
                            width: 1,
                          ),
                        ],
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
          Visibility(
            visible: layoutQty,
            child: Container(
              margin: const EdgeInsets.only(left: 15, top: 5, right: 15, bottom: 0),
              width: double.infinity,
              child: Row(
                children: [
                  Expanded(
                    flex: 1,
                    child: ConstrainedBox(
                      constraints: BoxConstraints(maxHeight: 40),
                      child: TextField(
                        controller: textEditingController,
                        textInputAction: TextInputAction.search,
                        onSubmitted: (String text) {
                          print('Searching for $text');
                        },
                        // autofocus: true,
                        decoration: InputDecoration(
                          border: OutlineInputBorder(
                            borderSide: BorderSide(
                              color: MyAppTheme.nearlyBlue,
                            ),
                            borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                          ),
                          enabledBorder: OutlineInputBorder(
                            borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                            // 设置焦点之外的边框颜色
                            borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                          ),
                          focusedBorder: OutlineInputBorder(
                            borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                            // 设置焦点时的边框颜色
                            borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                          ),
                          hintText: "please scan the dock num",
                          filled: true,
                          fillColor: MyAppTheme.white,
                          //隐藏下划线
                          //border: InputBorder.none,
                          hintStyle: TextStyle(color: Colors.grey),
                          contentPadding: const EdgeInsets.symmetric(vertical: 0, horizontal: 15),
                        ),
                      ),
                    ),
                  ),
                  Text(
                    "  Pallets QTY",
                    style: TextStyle(color: MyAppTheme.color_666666, fontSize: 14.0),
                  ),
                ],
              ),
            ),
          ),
          Container(
            margin: const EdgeInsets.only(left: 15, top: 15, right: 15, bottom: 0),
          ),
          Visibility(
            visible: tvPhoto,
            child: Text(
              'Damage(s):  ',
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
              style: TextStyle(color: MyAppTheme.color_666666, fontSize: 12.0),
            ),
          ),
          Visibility(
            visible: rv,
            child: Expanded(
              flex: 2, //设置权重
              child: setListView(8, damages),
            ),
          ),
        ],
      ),
    );
  }

  ListView setListView(int type, List<PhotoBean> data) {
    return ListView.builder(
      scrollDirection: Axis.horizontal,
      itemCount: data == null ? 0 : data.length,
      itemBuilder: (context, index) {
        PhotoBean photoBean = data[index];
        print(photoBean.toString());
        return Container(
          height: 70,
          width: 70,
          margin: const EdgeInsets.only(left: 0, top: 0, right: 10, bottom: 0),
          child: Stack(
            children: <Widget>[
              GestureDetector(
                onTap: () {
                  // 请求焦点
                  FocusScope.of(context).requestFocus(FocusNode());
                  this.index = type;
                  this.position = index;
                  ((photoBean.image == null) && Utils.isEmpty(photoBean.urlImg)) ? pickImages(context) : imgFileDialog(photoBean, Constants.baseImgUrl);
                },
                child: photoBean.image == null
                    ? (photoBean.urlImg == null
                        ? Image.asset(
                            'assets/images/add.png',
                            width: 70,
                            height: 70,
                            fit: BoxFit.cover,
                          )
                        : Image.network(
                            Constants.baseImgUrl + photoBean.urlImg,
                            width: 70,
                            height: 70,
                            fit: BoxFit.cover,
                          ))
                    : Image.file(
                        photoBean.image,
                        width: 70,
                        height: 70,
                        fit: BoxFit.cover,
                      ),
              ),
              Visibility(
                visible: ((photoBean.image == null) && Utils.isEmpty(photoBean.urlImg)) ? false : true,
                child: Positioned(
                  top: 2.0,
                  left: 53,
                  child: GestureDetector(
                    onTap: () {
                      setState(() {
                        data.removeAt(index);
                      });
                    },
                    child: Image.asset(
                      'assets/images/ic_delete_menu.png',
                      width: 15,
                      height: 15,
                    ),
                  ),
                ),
              ),
            ],
          ),
        );
      },
    );
  }

  @override
  void showFileUploadData(String path, int type, int position, bool isSubmit) {
    damages[position].urlImg = path;
    if (isSubmit) {
      submitData();
    }
  }

  @override
  void setNext() {
    ToastContext().init(context);
    if (Utils.isEmpty(strDate)) {
      Toast.show("Please select Drop Date", duration: Toast.lengthShort, gravity: Toast.bottom);
      return;
    }
    submitData();
  }

  void submitData() {
    CheckinPendingQr checkinPendingQr = new CheckinPendingQr();
    checkinPendingQr.id = checkinInfo.id;
    checkinPendingQr.dock = checkinInfo.checkinDock;
    checkinPendingQr.dropDate = strDate;

    if (checkinInfo.operationMethod == "container") {
      code = textEditingController.text;
      if (Utils.isEmpty(code)) {
        Toast.show("please scan the dock num", duration: Toast.lengthShort, gravity: Toast.bottom);
        return;
      }
      checkinPendingQr.dock = code;

      for (int i = 0; i < damages.length - 1; i++) {
        PhotoBean photoBean = damages[i];
        if (Utils.isEmpty(photoBean.urlImg)) {
          position = i;
          fileUpload(containerNo, "checkin", photoBean.image, "damage", 8, position, true, true);
        }
      }
    }
    checkSubmit(checkinInfo, checkinPendingQr);
  }

  @override
  void setReset() {
    setState(() {
      textEditingController.text = "";
      strDate = "";
      damages.clear();
      damages.add(new PhotoBean());
    });
  }

  void checkSubmit(CheckinInfo checkinInfo, CheckinPendingQr checkinPendingQr) async {
    String json = jsonEncode(checkinPendingQr);
    try {
      // 显示加载中对话框
      LoadingIndicator.show(context);
    } catch (e) {
      e.toString();
    }
    BaseResponse baseResponse = await NetworkManager().request(context, Constants.checkSubmit, method: BaseMethod.post, data: json);

    try {
      // 在需要的时候隐藏加载中对话框
      LoadingIndicator.hide();
    } catch (e) {
      e.toString();
    }

    if (baseResponse.status == 200) {
      CheckinPendingModel checkinPending = CheckinPendingModel.fromJson(baseResponse.data);
      if (checkinInfo.operationMethod == "container") {
        Navigator.pop(context, true);
      } else {
        Navigator.push(
          context,
          MaterialPageRoute(
              builder: (context) => CheckinVerify(
                    data: checkinInfo,
                    checkinPending: checkinPending,
                  )),
        ).then((value) => {Navigator.pop(context, value)});
      }
    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }
}
